<?php 
class testActions extends sfActions
{
    public function executeTest()
    {
        $ar = array(
            array(
                    "type" => "header"
                    , "data" => array(
                            array(
                                    // ID from ListValues
                                    1, "red"
                            )
                            , array(
                                    2, "blue"
                            )
                            , array(
                                    3, "white"
                            )
                    )
            )
            , array(
                    "type" => "label"
                    , "data" => "Pagal šuns kategoriją"
                    )
    
            , array(
                    "type" => "row"
                    , "data" => array(4, 0, 0)
                    )
            );
            
        $arHeadersColours = array();
            
        $totalR = count($ar);
        $s = "<table>";
        for( $row = 0; $row < $totalR; $row++ )
        {
            $countRows = count($ar[0]["data"]);
            switch( $ar[$row]["type"] )
            {
                case "header":
                    $totalCells = count($ar[$row]["data"]);
                    $s .= "<tr>";
                    for( $i = 0; $i < $totalCells; $i++ )
                    {
                        $arHeadersColours[$i] = $ar[$row]["data"][$i][1];
                        $s .= "<td style='background: " . $ar[$row]["data"][$i][1] . ";'>" . $ar[$row]["data"][$i][0] . "</td>";
                    }
                    $s .= "</tr>";
                    break;
                case "label":
                    $s .= "<tr>";
                    $s .= "<td COLSPAN=".($countRows +1)." style='background: white;'>" . $ar[$row]["data"] . "</td>";
                    $s .= "</tr>";
                    break;
                case "row":
                    $arrayRow = explode(':', $ar[$row]["data"]);
                    $totalCells = count($arrayRow);
                    $s .= "<tr>";
                    for( $i = 0; $i < $totalCells; $i++ )
                    {
                        if($arrayRow[$i]){
                        $s .= "<td style='background: " . $arHeadersColours[$i] . ";'>" . $arrayRow[$i] . "</td>";
                        }
                    }
                    $s .= "</tr>";
                    break;
            }
        }
            
        exit($s);
        $this->jsonAr = json_encode($ar);
    }
    public function executeSummary()
    {
        /* @var $info TempFileInfo */
        $info = $this->getUser()->getAttribute('cropInfo');
        $this->forward404Unless($info);
        $this->state = $info->getCountDirs();
        $this->echo = 'THE END.';
    }
    
    public function executeCrop()
    {
        /* @var $info TempFileInfo */
        $info = $this->getUser()->getAttribute('cropInfo');
        $this->forward404Unless($info);
        if($getState = $this->getRequestParameter('state'))
        {
            if($getState<0)
            {
                $getState = 1;
            }
            $info->setState($getState);
        }
        $state = $info->getState();
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            $name = $info->getFileName();
            $path = $info->getTempDir();
            $dir = $info->getDirByCurrentState();
            $file = $path .'/'.$name;
            $newFile = 'images/gallery/' . $dir .'/'.$name;
            if(!@copy($file, $newFile))
            {
                throw new Exception('Cannot make file copy');
            }
            $x1 = $this->getRequestParameter('x1');
            $y1 = $this->getRequestParameter('y1');
            $width = $this->getRequestParameter('width');
            $height = $this->getRequestParameter('height');
            $img = new sfImage($newFile, $info->getFileType());
            $cr = new ACrop($x1, $y1, $width, $height);
            $imgn = $cr->transform($img);
            $imgn->save();
            if( $state > $info->getCountDirs())
            {
                $this->redirect('test/summary');
            }else 
            {
                $info->setState($state+1);
                $this->getUser()->setAttribute('cropInfo', $info);
                $this->redirect('test/crop');
            }
        }else 
        {
            if( $state > $info->getCountDirs())
            {
                $this->redirect('test/summary');
            }
            $this->name = $info->getFileName();
            $this->path = $info->getTempDir();
            $this->state = $info->getState();
            $this->dir = $info->getDirByCurrentState();
            $this->h = $info->getHeightByState();
            $this->w = $info->getWidthByState();
        }
        
    }
    public function executeCancel()
    {
        $info = $this->getUser()->getAttribute('cropInfo');
        @unlink($info->getTempDir().'/'.$info->getFileName());
        foreach (Files::getPhotoDirs() as $key=>$dir )
        {
            @unlink('images/gallery/'.$key.'/'.$info->getFileName());
        }
        $this->getUser()->getAttributeHolder()->remove('cropInfo');
        $this->redirect('test/upload');
    }
    public function executeSave()
    {/* @var $info TempFileInfo */
//        $this->objType = MyConstants::TYPE_CATEGORY;
//        $this->objId = MyConstants::UNDEFINED_ID;
        $info = $this->getUser()->getAttribute('cropInfo');
        $this->forward404Unless($info);
        $directories = $info->getArDirectories();
        
        // foreach directories, where must be saved photos
        foreach ( $directories as $dir )
        {
            // if file wasn`t cropped, create automatic
            if(!file_exists('images/gallery/' . $dir['dir']. '/'.$info->getFileName()))
            {
                if(!@copy($info->getTempDir().'/'.$info->getFileName(), 'images/gallery/' . $dir['dir']. '/'.$info->getFileName()))
                {
                    throw new Exception('Cannot make file copy');
                }
            }
            Files::saveTo($info->getFileName()
                        , 'images/gallery/' . $dir['dir']. '/'.$info->getFileName()
                        , 111
                        , get_user_id()?get_user_id():111
                        , 111
                        , $this->getUser()->getCulture()
                        , MyConstants::STATUS_UNAVAILABLE
                        , $info->getFileName()
                        , ''
                        , array($dir['dir'] => $directories[$dir['dir']]));
        }
        @unlink($info->getTempDir().'/'.$info->getFileName());
        
        $this->getUser()->getAttributeHolder()->remove('cropInfo');
        $this->redirect('test/upload');
    }


    public function executeUpload()
    {
        //$objType and $objId must by set by used module data
        $this->objType = MyConstants::TYPE_CATEGORY;
        $this->objId = MyConstants::UNDEFINED_ID;
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            //save uploaded image in temporary directory, and save data about this file in session
            $fileName = $this->getRequest()->getFileName('photo');
            $filePath = $this->getRequest()->getFilePath('photo');
            $arFile = $this->getRequest()->getFile('photo');
            $bExt = substr($fileName, strrpos($fileName, '.') + 1);
            $ext = strtolower($bExt);
            $path = 'temporary';
            if (!file_exists($path))
            {
                @mkdir($path, 0777);
            }
            // TODO: generate name by objType and objId;
            $this->name = md5($fileName . time()) . '.' .  $ext;
            $newFile = $path . '/' . $this->name;
            $this->path = $path;
            if( !@copy($filePath, $newFile) )
                throw new Exception('File not uploaded.');
            $type = $arFile['type'];
            
            //save data about this file in session
            /* @var $info TempFileInfo */
            $info = new TempFileInfo();
            $info->setFileExtension($ext);
            $info->setFileName($this->name);
            $info->setFileType($type);
            $info->setTempDir($path);
            $info->setObjId($this->objId);
            $info->setObjType($this->objType);
            $info->setState(1);
            $this->getUser()->setAttribute('cropInfo', $info);
            
            $h = sfConfig::get('app_image_screen_size_h');
            $w = sfConfig::get('app_image_screen_size_w');
            list($width, $height) = getimagesize($newFile); 
            //check if image not to big for screen
            ACrop::reduceToWindowSize($h, $w, $height, $width, $newFile, $type);
            $this->dirs = Files::getPhotoDirs();
            $this->redirect('test/crop');
        }
    }
    public function executeParse()
    {
        $mask = '/(src=\\".+)(\\.com\\/.+?\\/)([^"|\\?]+)/';
        $this->video_src = '<object width="480" height="390"><param name="movie" value="http://www.youtube-nocookie.com/v/_p1aOVorIzs?fs=1&amp;hl=lt_LT"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/embed/_p1aOVorIzs?fs=1&amp;hl=lt_LT" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="390"></embed></object>';
        preg_match_all($mask, $this->video_src, $arMatches);
        debugvar($arMatches);
        //debugvar(parse_url($arMatches[2][0]));
        $this->setTemplate('index');
        sfView::NONE;
    }
    public function executeIndex()
    {
        //Get the XML document loaded into a variable
//        $xml = file_get_contents('example.xml');
//        debugvar($xml, 'xml');
//        //Set up the parser object
//        $parser = xml_parser_create();
//        $array = array();
//        $arr = xml_parse_into_struct($parser, $xml, $array);
//        debugvar($array, '$arr');
        
        //Work the magic...
        //$parser->Parse();
		//CurrencyExchange::loadExchangeRatio();        
    }

	public function executeGet() 
	{
		$arCurrencyExchange = CurrencyExchange::getExchangeRatio();
		
		debugvar($arCurrencyExchange, 'currencyChange');
		$this->setTemplate('index');
	}

	public function executeLogrotate() 
	{
		$arLog = LogRotate::rotate();
		
		//debugvar($arCurrencyExchange, 'currencyChange');
		$this->setTemplate('index');
	}
}